
const db = require("../core/DBhelper");
const moment = require("moment");

class MeunController {

    /**
* @api {post} sys/addMeun 添加菜单
* @apiVersion 1.0.0
* @apiName addRole
* @apiGroup Meun模块
* @apiParam {Number} parentId 父id
* @apiParam {String} parentName 父菜单名
* @apiParam {String} name 菜单名称
* @apiParam {String} direct 菜单表示 sys:meun
* @apiParam {String} url 路径  sys/meun
* @apiParam {String} type ""
* @apiParam {String} icon 菜单图标
* @apiParam {String} orderNum 菜单排序号
* @apiParam {String} open 是否默认打开 0
* @apiParam {String} list 
* @apiSuccess {Number} code 结果标识
* @apiSuccess {String} msg 结果说明
* @apiSuccessExample Success-Response:
* 
*  {
    code: 200,
    msg: "添加菜单成功"
}
*/
    async addMeun(req, res, next) {

        let add_sql = " INSERT INTO  `menus` (`parentId`,`parentName`,`name`,`direct`,`url`,`type`,`icon`,`orderNum`,`open`,`list`) ";
        add_sql += " VALUES(?,?,?,?,?,?,?,?,?,?)"

        let add_params = [
            req.body.parentId,
            req.body.parentName,
            req.body.name,
            req.body.direct,
            req.body.url,
            req.body.type,
            req.body.icon,
            req.body.orderNum,
            req.body.open,
            req.body.list
        ]

        let result = await db.exec(add_sql, add_params);
        let isAdd = result && result.affectedRows >= 1
        res.json({
            msg: isAdd ? "添加菜单成功" : "添加菜单失败",
            code: isAdd ? 200 : -200
        })

    }

    /**
* @api {post} sys/updateMeun 修改菜单
* @apiVersion 1.0.0
* @apiName updateMeun
* @apiGroup Meun模块
 *@apiParam {Number} menuId 菜单id
* @apiParam {Number} parentId 父id
* @apiParam {String} parentName 父菜单名
* @apiParam {String} name 菜单名称
* @apiParam {String} direct 菜单表示 sys:meun
* @apiParam {String} url 路径  sys/meun
* @apiParam {String} type ""
* @apiParam {String} icon 菜单图标
* @apiParam {String} orderNum 菜单排序号
* @apiParam {String} open 是否默认打开 0
* @apiParam {String} list 
* @apiSuccess {Number} code 结果标识
* @apiSuccess {String} msg 结果说明
* @apiSuccessExample Success-Response:
* 
*  {
*   code: 200,
*   msg: "修改菜单成功"
}
*/
    async updateMeun(req, res, next) {

        let update_sql = " UPDATE `menus` SET `parentId`=?,`parentName`=?,`name`=?,`direct`=?,`url`=?,`type`=?,`icon`=?,`orderNum`=?,`open`=?,`list`=? "
        update_sql += " WHERE `menuId` =? ;"

        let add_params = [
            req.body.parentId,
            req.body.parentName,
            req.body.name,
            req.body.direct,
            req.body.url,
            req.body.type,
            req.body.icon,
            req.body.orderNum,
            req.body.open,
            req.body.list,
            req.body.menuId,
        ]

        let result = await db.exec(update_sql, add_params);
        let isUpdata = result && result.affectedRows >= 1
        res.json({
            msg: isUpdata ? "修改菜单成功" : "修改菜单失败",
            code: isUpdata ? 200 : -200
        })

    }

    /**
* @api {post} sys/deleteMeun (软)删除菜单
* @apiVersion 1.0.0
* @apiName deleteMeun
* @apiGroup Meun模块
 *@apiParam {Number} menuId 菜单id
* @apiSuccess {Number} code 结果标识
* @apiSuccess {String} msg 结果说明
* @apiSuccessExample Success-Response:
* 
*  {
*     code: 200,
*     msg: "删除菜单成功"
*  }
*/
    async deleteMeun(req, res, next) {
        let sql = " UPDATE `menus` SET  `status`=0 WHERE `menuId` =? ;"
        let parmas = [req.body.menuId]

        let result = await db.exec(sql, parmas)
        let isDelete = result && result.affectedRows >= 1
        res.json({
            msg: isDelete ? "删除菜单成功" : "删除菜单失败",
            code: isDelete ? 200 : -200
        })
    }

    /**
* @api {get} sys/getMeuns 获取所有的菜单
* @apiVersion 1.0.0
* @apiName getMeuns
* @apiGroup Meun模块
* @apiSuccess {Number} code 结果标识
* @apiSuccess {String} msg 结果说明
* @apiSuccessExample Success-Response:
* 
*  {
*       msg: "查询成功"
*       code: 200 
*       data: [] 递归的树
*  }
*/
    async getMeuns(req, res, next) {
        let sql = " SELECT * FROM menus ;"
        let parmas = []

        let result = await db.exec(sql, parmas)
        let isDelete = result && result.length >= 1;

        let self = this;
        res.json({
            msg: isDelete ? "查询成功" : "查询失败",
            code: isDelete ? 200 : -200,
            data: treeData(result)
        })
    }

    /**
    * @api {get} sys/getMeunsByRole 获取当前角色的菜单
    * @apiVersion 1.0.0
    * @apiName getMeunsByRole
    * @apiGroup Meun模块
    * @apiParam {Number} rId 角色id
    * @apiSuccess {Number} code 结果标识
    * @apiSuccess {String} msg 结果说明
    * @apiSuccessExample Success-Response:
    * 
    *  {
    *       msg: "查询成功"
    *       code: 200 
    *       data: []  // menuId 菜单
    *  }
    */
    async getMeunsByRole(req, res, next) {
        let sql = " SELECT menuId FROM permission WHERE rId=? AND `status`=1;";
        let params = [
            req.query.rId
        ]
        let result = await db.exec(sql, params)
        let isQuery = result && result.length >= 1
        res.json({
            msg: isQuery ? "查询成功" : "查询失败",
            code: isQuery ? 200 : -200,
            data: result.reduce((pre, cur) => { pre.push(cur.menuId); return pre }, [])   //  [{menuId:1},{menuId:2}]
        })
    }


/**
* @api {get} sys/updateMeunsByRole 角色设置菜单
* @apiVersion 1.0.0
* @apiName getMeunsByRole
* @apiGroup Meun模块
* @apiParam {Number} rId 角色id
* @apiParam {Array} menuIdList  菜单编号
* @apiSuccess {Number} code 结果标识
* @apiSuccess {String} msg 结果说明
* @apiSuccessExample Success-Response:
* 
*  {
*       msg: "添加菜单成功"
*       code: 200 
*  }
*/
    async updateMeunsByRole(req, res, next) {
        //1.根据角色id删除当前所有的菜单
        let sql = " DELETE FROM permission WHERE rId=? ;"
        let params = [
            req.body.rId
        ]
        let result = await db.exec(sql, params);
        //2.添加菜单id
        let menuIdList = JSON.parse(req.body.menuIdList || '[]');

        //menuIdList [menuId,menuId,menuId...]
        let isAddMeun = true;
        menuIdList.forEach(async item => {
            let sql_Add_perms = "INSERT INTO  permission (rId,menuId,`STATUS`)VALUES(?,?,1);";
            let prams_add_perms = [
                req.body.rId,
                item
            ]
            let addMeunId = await db.exec(sql_Add_perms, prams_add_perms);
            if (!addMeunId) {
                isAddMeun = false;
            }
        })
        res.json({
            msg: isAddMeun ? "添加菜单成功" : "添加菜单失败",
            code: isAddMeun ? 200 : -200
        })
    }


}



function treeData(list, id = 0) {
    let arr = list.filter(item => item.parentId == id);
    arr.forEach(item => {
        list.forEach(function (item2) {
            if (item.menuId == item2.parentId) {
                item.children = treeData(list, item2.parentId)
            }
        })
    });
    return arr
}

module.exports = new MeunController()